package Product

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/User/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type GetProductByClass struct {
	beego.Controller
}

func (c *GetProductByClass) GetProductByClass() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Product/GetProductByClass"
	res := resMes.GetClassification{}
	classification := &Admin.Classification{}
	log := &error2.Log{}
	var err error
	mes := &error2.Mes{}

	classId := c.GetString("classId")
	begin, err := c.GetInt("begin", 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	filter, err := c.GetInt("filter", 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	//fmt.Println(begin)

	err = GetProductByClassId(classId, classification, begin, filter)
	if err != nil {
		if err.Error() == "noMore" {
			c.Data["json"] = errorDeal.ErrLightMess(mes, "201", "noMore")
		} else {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		}
		return
	}
	res.Classification = classification
	res.Code = "200"
	c.Data["json"] = res
}

func GetProductByClassId(classId string, classification *Admin.Classification, begin int, filter int) (err error) {
	o := orm.NewOrm()
	sql := "select * from `classification` where classification_id=?"
	err = o.Raw(sql, classId).QueryRow(&classification)
	if err != nil {
		return
	}
	fmt.Println(filter)

	if filter == 0 {
		sql = "select * from `product_detailed` left join `classification_product_detaileds` on `product_detailed`.`product_id`=`classification_product_detaileds`.`product_detailed_id` where `classification_product_detaileds`.`classification_id`=? order by`classification_product_detaileds`.`id` desc limit ?,?"

	} else {
		sql = "select * from `product_detailed` left join `classification_product_detaileds` on `product_detailed`.`product_id`=`classification_product_detaileds`.`product_detailed_id` where `classification_product_detaileds`.`classification_id`=? order by `" + models.FilterList[filter-1][0] + "` " + models.FilterList[filter-1][1] + " limit ?,?"

	}
	num, err := o.Raw(sql, classification.ClassificationId, begin, begin+models.DateLengthByProduct).QueryRows(&classification.ProductDetailed)
	if num == 0 {
		err = fmt.Errorf("noMore")
		return
	}
	return nil
}
